<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/01/09
 * Time: 15:17
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\fac;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\FinanceBank;
use app\common\model\FinanceCash;
use app\common\model\FinanceInvoiceSetting;
use app\common\model\JobFlowModule;
use app\common\model\SysAttachment;
use app\common\service\finance\FinanceService;
use app\common\service\system\SystemService;
use app\common\status\BaseStatus;
use think\facade\Validate;

/**
 * 收款单管理
 * Class CashController
 * @package app\admin\controller\fac
 */
class CashController extends BaseController
{
    protected $moduleName = 'finance_cash';

    /**
     * 收款单列表
     * @date 2021/01/09
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $order = $this->request->post('order', 'biz_date');
            $cash = FinanceCash::with(['cashUser'])->order($order);
            $this->searchModel($cash, [
                'eq' => ['cash_type', 'cash_status', 'ref_type', 'is_invoice', 'account', 'check_status', 'ref_sn'],
                'like' => ['pay_user'],
                'times' => ['biz_date', 'real_date']
            ]);
            $limit = $this->getPageSize();
            $cash = $cash->paginate($limit);
            $this->assign('cash_status_none', FinanceCash::CASH_STATUS_WAIT);
            $this->assign("list", $cash->getCollection());
            $this->assign("page", $cash->render());
            return $this->fetch('lists');
        }
        $this->assign('sort', [
            'biz_date' => '待收款日期',
            'real_date' => '已收款日期',
            'cash_money' => '应该收金额',
            'real_money' => '已收金额',
        ]);
        $this->assign('order', ['asc', 'desc']);
        $this->assign('cash_type', FinanceCash::$CASH_TYPE);
        $this->assign('cash_status', FinanceCash::$CASH_STATUS);
        $this->assign('is_invoice', ['否', '是']);
        $this->assign('ref_type', BaseStatus::$REF_TYPE);
        $this->assign('check_status', JobFlowModule::$CHECK_STATUS);
        $this->assign('banks', FinanceBank::getAll());
        return $this->fetch('index');
    }

    /**
     * 收款单详情
     * @date 2021/02/05
     * @author longli
     */
    public function info()
    {
        $cashId = $this->request->get('cash_id');
        if(empty($cashId)) $this->error("非法请求");
        $cash = FinanceCash::get($cashId);
        if(empty($cash)) $this->error("收款单不存在");
        $this->assign("attachment_type_invoice", SysAttachment::FILE_TYPE_INVOICE);
        $this->assign("attachment_type_contract", SysAttachment::FILE_TYPE_CONTRACT);
        $this->assign('attachment_type_other', SysAttachment::FILE_TYPE_OTHER);
        $this->assign("is_show_check", JobFlowModule::isCheckIng($cash)
            && $this->user->hasPermissions('/fac/cash/check')
        );
        $this->assign("cash_info", $this->renderInfo($cash));
        $this->assign("is_show_cash",
            in_array($cash->getData('cash_status'), [FinanceCash::CASH_STATUS_WAIT, FinanceCash::CASH_STATUS_PART])
            && JobFlowModule::isCheckFinish($cash)
            && $this->user->hasPermissions('/fac/cash/save')
        );
        if($cash->getData('check_status') != JobFlowModule::CHECK_NO_NEED)
        {
            $this->assignCheck($cashId);
        }
        $this->assign('cash', $cash);
        return $this->fetch('info');
    }

    /**
     * 添加收款单
     * @date 2021/02/05
     * @author longli
     */
    public function save()
    {
        if($this->request->isPost())
        {
            $validate = Validate::make([
                'cash_id'  => 'require',
                'cash_type'  => 'require',
                'account'  => 'require',
                'service_charge'  => 'require|egt:0',
                'real_money'  => 'require|gt:0',
                'pay_company'  => 'require',
                'pay_account'  => 'require',
                'pay_user'  => 'require',
            ],[
                'cash_id.require' => '非法请求',
                'cash_type.require' => '收款方式必选',
                'account.require' => '收款账号必选',
                'service_charge.require' => '手续费必填',
                'service_charge.egt' => '手续费必需大于等于0',
                'pay_company.require' => '付款付款单位必填',
                'pay_account.require' => '付款账号必填',
                'pay_user.require' => '付款人必填',
                'real_money.require' => '付款金额必填',
                'real_money.gt' => '付款金额必需大于0',
            ]);
            $data = $this->request->post();
            if(!$validate->batch()->check($data)) $this->error(join(', ', $validate->getError()));
            if(!JobFlowModule::isCheckFinish(FinanceCash::get($data['cash_id']))) return "收款单未审批通过，不能收款";
            if($data['cash_money'] - $data['service_charge'] != $data['real_money']) $this->error("付款金额错误");
            $data += [
                'cash_status' => FinanceCash::CASH_STATUS_ALL,
                'real_date' => Tools::now(),
                'cash_user_id' => $this->user->id,
            ];
            FinanceService::getInstance()->addCash($data)
                ? $this->success("添加收款成功")
                : $this->error("添加收款失败");
        }
        // 展示添加收款单
        $cashId = $this->request->get("cash_id");
        $cash = FinanceCash::get($cashId);
        if(empty($cash)) $this->error("付款单不存在");
        $this->assign('cash', $cash);
        $this->assign('cash_type', FinanceCash::$CASH_TYPE);
        $this->assign("banks", FinanceBank::getAll());
        $this->assign("invoices", FinanceInvoiceSetting::getAll());
        return $this->fetch('save_cash');
    }

    /**
     * 上传收款单据
     * @date 2021/02/05
     * @author longli
     */
    public function upload()
    {
        $validate = Validate::make([
            'cash_id'  => 'require',
            'type'  => 'require',
            'path'  => 'require',
        ],[
            'cash_id.require' => '非法请求',
            'type.require' => '类型必传',
            'path.require' => '文件路径必传',
        ]);
        $data = $this->request->post();
        if(!$validate->batch()->check($data)) $this->error($validate->getError());
        $rootPath = FinanceService::getRootPath($data['path']);
        if(!is_file($rootPath)) $this->error("上传失败");
        if(SysAttachment::hasFile($rootPath)) $this->success("上传成功");
        $data += [
            'md5_code' => md5_file($rootPath),
            'id_type' => FinanceCash::getTable(),
            'ref_id' => $data['cash_id'],
        ];
        SystemService::getInstance()->addAttachment($data)
            ? $this->success("上传成功")
            : $this->error("上传失败");
    }

    /**
     * 渲染自定义收款详情模板
     * @param FinanceCash $cash 收款或者收款数据模型
     * @return string|void
     * @date 2021/01/11
     * @author longli
     */
    private function renderInfo($cash)
    {
        if(empty($cash->ref_sn)) return;
        $classes = '\\app\\common\\model\\' . ucfirst(Tools::toCamelCase($cash->ref_id_type));
        return $this->renderTerp($classes, $cash->ref_sn, "pur/purchase/info/{$cash->getData('ref_type')}");
    }
}